package com.gitee.base.modules.core.controller;

import com.gitee.base.modules.BaseController;
import com.gitee.base.modules.core.model.SysRole;
import com.gitee.base.modules.core.model.SysUser;
import com.gitee.base.modules.core.service.ISysRoleService;
import com.gitee.base.modules.core.service.ISysUserService;
import com.gitee.base.security.permission.annotation.RequiresPermissionsDesc;
import com.gitee.base.utils.JsonVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by yang on 2018/5/8.
 */
@Controller
@RequestMapping("/core/my")
public class CoreMyController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;

    @RequiresPermissionsDesc(folder = "我的",menu = "个人信息",button = "查看",page = true)
    @RequiresPermissions("core:my:info")
    @GetMapping("/info")
    public String info(ModelMap modelMap) {
        try {
            List<SysRole> roleList = this.sysRoleService.listByIds(Stream.of(getLoginUser().getRoleIds().split(",")).collect(Collectors.toList()));
            if (roleList != null && !roleList.isEmpty()) {
                modelMap.put("roleList", roleList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "core/my/info";
    }

    @RequiresPermissionsDesc(folder = "我的",menu = "修改密码",button = "修改密码",page = true)
    @RequiresPermissions("core:my:repwd")
    @GetMapping("/repwd")
    public String repwd(ModelMap modelMap) {
        return "core/my/repwd";
    }

    @RequiresPermissions("core:my:repwd")
    @PostMapping("/repwd/validate")
    @ResponseBody
    public JsonVo repwdValidate(@RequestParam String oldPwd, @RequestParam String pwd, @RequestParam String rePwd) {
        try {
            if (!StringUtils.equals(pwd, rePwd)) {
                return JsonVo.fail(500, "两次密码输入不一致");
            }
            SysUser sysUser = getLoginUser();
            if (!StringUtils.equals(sysUser.getPassword(), DigestUtils.md5Hex(oldPwd))) {
                return JsonVo.fail(500, "原密码不正确");
            }

            SysUser t = new SysUser();
            t.setId(sysUser.getId());
            t.setPassword(DigestUtils.md5Hex(pwd));
            this.sysUserService.updateById(t);
            return JsonVo.success();
        } catch (Exception e) {
            logger.error("MyController.repwdValidate", e);
        }
        return JsonVo.fail();
    }

}
